﻿
using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using SiteManager;
using System.Text;
using System.Data.SqlClient;
using System.Net.Mail;
using System.IO;
using System.Collections.Generic;
using System.Collections.Specialized;


public partial class Community_FacePage : System.Web.UI.Page
{
    Manager mgr = new Manager(true,"ConnectionString");
    public enum FeaturedDoctorType { NonFeatured, Standard, Enhanced, Premium };
    string sDescription = "";
    int DoctorId = 0;
    //int eSenderType = 0;
    int eReceiverType = 0;

    int acceptorID = 0;
    
    string strMailBody, sUserEmail = "", strSubject = "", strEmailTo = "", strDoctorName = "" ,receiverType="";
    protected void Page_Load(object sender, EventArgs e)
    {
        lblMessage.Visible = false;
        if (!IsPostBack)
        {
             Session["isReply"] = "false";
             localFunction lfunction = new localFunction();
             if (Session["DoctorType"].ToString() == "Doctor")
             {
                 lfunction.checkDoctorLogin(true);
                 tbl_Doctor doc = CustomRepository.GetReceiverDoctor(Convert.ToInt32(Session["userID"]));
                 string fullName = doc.FName + " " + doc.MName + " " + doc.LName;
                 lblBlockOwner.Text = "Dr." + " " + fullName + ":" + "This is your SECURE personal Face Page ";
             }
             else if (Session["DoctorType"].ToString() == "Dentist")
             {
                lfunction.checkDentistLogin(true);
                 tbl_Dentist doc = CustomRepository.GetReceiverDentists(Convert.ToInt32(Session["userID"]));
                 string fullName = doc.FName + " " + doc.MName + " " + doc.LName;
                 lblBlockOwner.Text = "Dr." + "" + fullName + ":" + "This is your SECURE personal Face Page ";
             }
             else
             {
                 if (string.IsNullOrEmpty(Session["userID"].ToString()))
                 {
                     ClientScript.RegisterStartupScript(typeof(Page), "MessagePopUp", "alert('Access Denied ! You must be logged in as a Doctor or Dentist for Access.\\n\\nOn Return to the Home Page, please log in now with your email ID and your assigned Pass-Word (temp1234)'); window.location.href = '" + Session["strHttp"].ToString() + "default.aspx" + "';", true);
                     Session["FacePageURL"] = Session["strHttp"].ToString() + "Community/FacePage.aspx"; 
                     return;
                 }

             }
            txtPostReply.Visible = false;
            LoadFacePage();

            int Id = (Convert.ToInt32(Session["DentistDoctorID"]));
            string IDs = Convert.ToString(Id);
            List<string> receverId = CustomRepository.GetReciverIds(Convert.ToInt32(Session["userID"]));
            List<string> senderId = CustomRepository.GetSenderIds(Convert.ToInt32(Session["userID"]));
            if (Request.QueryString["Page"] == null)
            {
                if (!receverId.Contains(IDs) && !senderId.Contains(IDs))
                {
                    ckEditBlock.Visible = true;
                    lblPostTitle.Text = "Send  message for Dr. " + Session["DoctorDentistName"].ToString();// Session["DoctorName"];
                }
                else
                {
                    if (!string.IsNullOrEmpty(Convert.ToString(Session["StrEmailToID"])))
                    {
                        MessageTO(Convert.ToInt32(Session["StrEmailToID"]));
                    }
                    ckEditBlock.Visible = true;
                }
            }
            else
            {
                string myfacePage = Request.QueryString["Page"];
                if (myfacePage == "myFacePage")
                {
                    ckEditBlock.Visible = false; ;
                }
            }

        }
      
          
           // else
            //{
               // lblPostTitle.Text = "Send  message for Dr. " + Session["DoctorDentistName"].ToString();// Session["DoctorName"];
            //}
    }
    private void MessageTO(int id)
    {
        FacePage fp = CustomRepository.GetFaceGageMessage(id);
        string DoctorOrDentist = Convert.ToString(Session["FriendReqSenderType"]);
        if (DoctorOrDentist == "Doctor")
        {
            tbl_Doctor doc = CustomRepository.GetReceiverDoctor(id);
            string fullName = doc.FName + " " + doc.MName + " " + doc.LName;
            lblPostTitle.Text = "Message To:" + "" + fullName;

        }
        else
        {
            tbl_Dentist doc = CustomRepository.GetReceiverDentists(id);
            string fullName = doc.FName + " " + doc.MName + " " + doc.LName;
            lblPostTitle.Text = "Message To:" + "" + fullName;

        }
    }
    /// <summary>
    /// This function will return Message Posted by a doctor
    /// </summary>
    public void LoadFacePage()
    {
        Manager objManager = new Manager(true,"ConnectionString");
        SqlDataReader objDataReader = null;
        DoctorId = Convert.ToInt32(Session["userID"]);
        string SQLBlog = string.Empty;

        if (Session["DoctorType"].ToString() == "Dentist")
            SQLBlog = "SELECT (FName+' '+MName+' '+LName) AS Name FROM tbl_Dentists WHERE id = " + DoctorId;
        else if ((Session["DoctorType"].ToString() == "Doctor"))
            SQLBlog = "SELECT (FName+' '+MName+' '+LName) AS Name FROM tbl_Doctors WHERE id = " + DoctorId;


        
        objDataReader = objManager.ExecuteQuery("select * from FacePage where ReceiverId=" + Convert.ToInt32(Session["userID"]));
      
        BindGrid(Convert.ToInt32(Session["userID"]));
        objManager = null;
    }
    public void LoadInvitationMessage()
    {
        Manager objManager = new Manager(true, "ConnectionString");
        SqlDataReader objDataReader = null;
        DoctorId = Convert.ToInt32(Session["userID"]);
        string SQLBlog = string.Empty;

        if (Session["DoctorType"].ToString() == "Dentist")
            SQLBlog = "SELECT (FName+' '+MName+' '+LName) AS Name FROM tbl_Dentists WHERE id = " + DoctorId;
        else if ((Session["DoctorType"].ToString() == "Doctor"))
            SQLBlog = "SELECT (FName+' '+MName+' '+LName) AS Name FROM tbl_Doctors WHERE id = " + DoctorId;

        objDataReader = objManager.ExecuteQuery("select * from FacePage where ReceiverId=" + Convert.ToInt32(Session["userID"]));
       

        GetImageMessage(Convert.ToInt32(Session["userID"]));
        objManager = null;
    }
    string rteSafe(string str)
    {
        string tmpString = str;
        tmpString = tmpString.Replace(Convert.ToChar(145), Convert.ToChar(39));
        tmpString = tmpString.Replace(Convert.ToChar(146), Convert.ToChar(39));
        tmpString = tmpString.Replace("'", "&#39;");
        //	'convert all types of double quotes
        tmpString = tmpString.Replace(Convert.ToChar(147), Convert.ToChar(34));
        tmpString = tmpString.Replace(Convert.ToChar(148), Convert.ToChar(34));
        //	'replace carriage returns & line feeds
        tmpString = tmpString.Replace(Convert.ToChar(10), Convert.ToChar(" "));
        tmpString = tmpString.Replace(Convert.ToChar(13), Convert.ToChar(" "));
        return tmpString;
    }

    //ADD CODE TO DISPLAY/EDIT/VIEW ALL FacePages OF DOCTORS
    private void BindGrid(int id)
    {
        Manager mgrobj = new Manager(true,"ConnectionString");
        string sql = "";
       // sql = "select ID,FacePageTitle,FacePagePostedDate from FacePage where ReceiverId=" + Convert.ToInt32(Session["userID"]) + "ORDER BY FacePagePostedDate DESC ";
        SqlParameter[] sqlParam = new SqlParameter[1];
        sqlParam[0] = new SqlParameter("@UserId", SqlDbType.Int);
        sqlParam[0].Value = Convert.ToInt32(Session["userID"]);
        DataSet ds = mgrobj.ExecuteQuery("GetMessageSender", sqlParam, "tbl");
        if (ds.Tables[0].Rows.Count > 0)
        {
            grdMessages.DataSource = ds.Tables[0];
            grdMessages.DataBind();
           
        }
        else // no topics exist
        {
            grdMessages.DataSource = ds.Tables[0];
          
            grdMessages.DataBind();
            lblMessage.Visible = true;
            lblMessage.Text = "No Face Page Message exist for you!!";
            lblMessage.ForeColor = System.Drawing.Color.Red;
            ckEditBlock.Visible = true;
            
            return;
        }
        mgrobj = null;
    }
    private void GetImageMessage(int id)
    {
         Manager mgrobj = new Manager(true, "ConnectionString");
        string sql = "";
         sql = "select ID,FacePageMessage from InvitationMessage where ReceiverId=" + Convert.ToInt32(Session["userID"]) + "";
          DataSet ds = mgrobj.ExecuteQuery(sql, "tbl");
        if (ds.Tables[0].Rows.Count > 0)
        {
            grgInvitationMsg.DataSource = ds.Tables[0];
            //grdMessages.PageSize = Convert.ToInt32(Session["AdminPageSize"]);
            grgInvitationMsg.DataBind();
        }
        else // no topics exist
        {
            grdMessages.DataSource = ds.Tables[0];
            //grdMessages.PageSize = Convert.ToInt32(Session["AdminPageSize"]);
            grdMessages.DataBind();
            lblMessage.Visible = true;
            lblMessage.Text = "No Face Page Message exist for you!!";
            lblMessage.ForeColor = System.Drawing.Color.Red;
            return;
        }
        mgrobj = null;
    }
    protected void btnSubmitt_Click(object sender, EventArgs e)
    {
        string isReply=Convert.ToString( Session["isReply"]);
        if ( isReply== "true")
        {
            Reply();
           
        }
        else
        {
            #region Parameters 
            if (txtFacePageTitle.Text.ToString() == "")
            {
                lblMessage.Visible = true;
                lblMessage.Text = "Write Face Page Title";
                return;
            }

            if (txtDescription.Text.ToString() == "")
            {
                lblMessage.Visible = true;
                lblMessage.Text = "Write into Face Page message";
               }
            Manager objManger = new Manager(true, "ConnectionString");
            int userType = 0;  //WILL USE TO SET ZERO(0) FOR DOCTOR AND 1 FOR DENTIST
            if ((Session["userType"].ToString() == "Doctor") && ((Convert.ToString(Session["DoctorType"])) == "Doctor"))
                userType = 2;
            else if (Session["userType"].ToString() == "SiteUser")
                userType = 3;
            else if ((Session["userType"].ToString() == "Doctor") && (Convert.ToString(Session["DoctorType"]) == "Dentist"))
                userType = 4;
            SqlParameter[] objSqlParameter = new SqlParameter[10];
            objSqlParameter[0] = new SqlParameter("@Id", SqlDbType.BigInt);
           if (btnSubmitt.Text.ToUpper().Trim() == "Update".ToUpper().Trim())
            {
                objSqlParameter[0].Value = Convert.ToInt32(Session["FacePageEditID"].ToString());
            }
            else
            {
                objSqlParameter[0].Value = 0;
            }
            objSqlParameter[1] = new SqlParameter("@SenderID", SqlDbType.BigInt);
            objSqlParameter[1].Value = Convert.ToInt32(Session["userID"]);
            objSqlParameter[2] = new SqlParameter("@SenderType", SqlDbType.BigInt);
            objSqlParameter[2].Value = userType;
            objSqlParameter[3] = new SqlParameter("@ReceiverID", SqlDbType.BigInt);
             objSqlParameter[3].Value = Convert.ToInt32(Session["DentistDoctorID"]);
            objSqlParameter[4] = new SqlParameter("@ReceiverType", SqlDbType.BigInt);
            if (Session["DentistDoctorID"] == null)
                objSqlParameter[4].Value = Convert.ToInt32(Session["eSenderType"]);
            else
                objSqlParameter[4].Value = Convert.ToInt32(Session["ReceiverType"]);
            objSqlParameter[5] = new SqlParameter("@FacePageMessage", SqlDbType.Text);
            if (Convert.ToInt32(objSqlParameter[0].Value) == 0)
            {
                objSqlParameter[5].Value = txtDescription.Text;
            }
            else
            {
                objSqlParameter[5].Value = txtDescription.Text + "<br />" + "<br />"; ;
                objSqlParameter[5].Value += "Reply from: " + Session["LoginName"].ToString();// +"<br />";
                objSqlParameter[5].Value += " on " + DateTime.Now.ToString("MM/dd/yyyy") + " at ";
                objSqlParameter[5].Value += DateTime.Now.ToString("hh:mm:ss tt") + "<br />";
                objSqlParameter[5].Value += txtPostReply.Text;
            }
            objSqlParameter[6] = new SqlParameter("@FacePageTitle", SqlDbType.Text);
            objSqlParameter[6].Value = txtFacePageTitle.Text.ToString().Trim();
            objSqlParameter[7] = new SqlParameter("@IsAddOrUpdate", SqlDbType.Bit);
            objSqlParameter[7].Direction = ParameterDirection.Output;
            objSqlParameter[8] = new SqlParameter("@FacePagePostedDate", SqlDbType.DateTime);
            objSqlParameter[8].Value = System.DateTime.Now;
            objSqlParameter[9] = new SqlParameter("@IsRead", SqlDbType.Bit);
            objSqlParameter[9].Value = false; ;   
            #endregion 

            #region mail
            if (Session["UserEmail"] != null && Session["UserEmail"].ToString().Trim() != "")
            {
                sUserEmail = Session["UserEmail"].ToString(); //This is Email From Address 
            }

            if (Session["DentistDoctorEmail"] != null && Session["DentistDoctorEmail"].ToString().Length != 0)
                strEmailTo = Session["DentistDoctorEmail"].ToString();
            else
            {
                strEmailTo = GetUserEmailAddress(Convert.ToInt32(Session["StrEmailToID"]), Convert.ToInt32(objSqlParameter[4].Value));// added by Wahaj Jan 20 2012 
            }

            if (strEmailTo.Trim() == "")
            {
                strEmailTo = "docfriend@findadoc.com";
                strDoctorName = GetUserName(Convert.ToInt32(Session["StrEmailToID"]), 0);// added by Wahaj Jan 20 2012 ;
            }
            if (Session["DentistDoctorID"] == null)
                strDoctorName = GetUserName(Convert.ToInt32(Session["StrEmailToID"]), Convert.ToInt32(objSqlParameter[4].Value));// added by Wahaj Jan 20 2012 ;
            else
                strDoctorName = Convert.ToString(Session["DoctorDentistName"]);
           
            int recieverId = (Convert.ToInt32(Session["DentistDoctorID"]));
            int Id = (Convert.ToInt32(Session["userID"]));
            string IDs = Convert.ToString(recieverId);
            List<string> receverId = CustomRepository.GetReciverIds(Convert.ToInt32(Session["userID"]));
            List<string> senderId = CustomRepository.GetSenderIds(Convert.ToInt32(Session["userID"]));
            string acceptReq = Session["AcceptRequest"].ToString();
            DataSet ds = GetDoctorPhoto();
            string drImage = getPhoto(ds.Tables[0].Rows[0][11], ds.Tables[0].Rows[0][12]);
            string DoctorOrDentist = Convert.ToString(Session["isDoctorOrDentist"]);
            string type = "";
            if (DoctorOrDentist == "Doctor")
            {
                type = "Doctor";
            }
            else
            {
                type = "Dentist";
            }
            if (!receverId.Contains(IDs) && !senderId.Contains(IDs))
            {
             SendFrienshipMail(Id, recieverId, drImage,type);

            }
            else if (acceptReq == "AcceptReq")
            {
                 AcceptFriendshipMail(Id, recieverId, drImage,type);
            }
            else
            {
                NewMail(Id, recieverId, drImage,type);
            }
            #endregion
            //////////////////////////

            # region add message
                          

            objManger.ExecuteQuery("AddandUpdateFacePage", objSqlParameter);
            if (Convert.ToInt32(objSqlParameter[0].Value) == 0)
            {
                lblMessage.Visible = true;
                lblMessage.Text = "Face Page Inserted successfully.";
                lblMessage.Font.Bold = true;
                clear_blockEditor();
            }
            else
            {
                lblMessage.Visible = true;
                lblMessage.Text = "Face Page Updated Successfully.";
                lblMessage.Font.Bold = true;
                 clear_blockEditor();
            }
            # endregion
            objManger = null;

            btnSubmitt.Text = "Post";
            LoadFacePage();
        }
    }

    private void SendFrienshipMail(int Id,int recieverId, string drImage,string type)
    {
        string DoctorOrDentist = Session["isToDoctorOrDentist"].ToString();
        if (DoctorOrDentist == "Doctor")
        {
            receiverType = "doctor";
            strMailBody = @"<div style='float:left;margin-right:15px;margin-bottom:5px'><span>"+drImage+"</span></div><br />";
            strMailBody = strMailBody + @"<span style=""font-size:12px""><span style='font-family:Arial;color:rgb(70,52,255);font-size:12px'>" + Session["LoginName"].ToString() + " is trying to connect with " + strDoctorName + "<br />";
            strMailBody = strMailBody + @"Click on <a href='http://www.findadoc.com/doctor/doctorLogin.aspx?id=" + Id + "&recieverId=" + recieverId + "&type=" + type + "&receiverType=" +receiverType+ "'target='_blank'><span style='font-family:Arial;color:rgb(70,52,255);font-size:12px'><b><u>ACCEPT</u></b></a> to connect with your colleague.</span></span><br />";
            strMailBody = strMailBody + @"<span style=""font-family:Arial;color:rgb(70,52,255);font-size:12px""><ul><li>Doc-Friend is restricted to Doctors and Dentists only. The 'Access Denied' warning will appear if you have not logged in.</li>";
            strMailBody = strMailBody + @"<li>Use your e-mail address as your ID. A temporary password, " + "<i>temp1234,</i>" + " can be substituted if needed. You can register later.</li></ul></span><br />";
            strMailBody = strMailBody + @"<span style=""font-family:Arial;color:rgb(70,52,255);font-size:12px"">The message from " + Session["LoginName"].ToString() + " will appear on your Personal </span>";
            strMailBody = strMailBody + @"<a href =""http://www.findadoc.com/Community/community.aspx"" target=""_blank""><span style=""font-family:Arial;color:rgb(70,52,255);font-size:12px""><b><u>Doctor Face Page</u></b></a></span><br />";
            strMailBody = strMailBody + @"<span><img height=""50"" width=""100"" src=""http://www.findadoc.com/images/logo.jpg""/><span style=""FONT-FAMILY:Arial;COLOR:rgb(0,0,0);FONT-SIZE:12px"">";
            strMailBody = strMailBody + @"<span style=""WHITE-SPACE:pre-wrap""></span></span>&nbsp; &nbsp; <span style=""COLOR:rgb(0,0,0);FONT-SIZE:12px"">&quot;Connect the Docs&quot; on Findadoc</span></span>";
            strSubject = @"Message from " + Session["LoginName"].ToString() + " via Doc Friend @ Findadoc";
            string strMessageStatus = SendEmailToDoctorDentist(strMailBody, strEmailTo, Session["LoginName"].ToString(), strSubject, sUserEmail);
            if (strMessageStatus == "Send Successfully")
            {
                ClientScript.RegisterStartupScript(typeof(Page), "MessagePopUp", "alert('Message Sent Successfully');", true);
            }
            else
            {
                ClientScript.RegisterStartupScript(typeof(Page), "MessagePopUp", "alert('" + strMessageStatus + "');", true);
            }
        }
        else if (DoctorOrDentist == "Dentist")
        {
            receiverType = "dentist";
            strMailBody = @"<div style='float:left;margin-right:15px;margin-bottom:5px'><span>"+drImage+"</span></div><br />";

            strMailBody = strMailBody + @"<span style=""font-size:12px""><span style='font-family:Arial;color:rgb(70,52,255);font-size:12px'>" + Session["LoginName"].ToString() + " is trying to connect with " + strDoctorName + "<br />";
            strMailBody = strMailBody + @"Click on <a href='http://www.findadoc.com/Dentist/DentistLogin.aspx?id=" + Id + "&recieverId=" + recieverId + "&type=" + type + "&receiverType=" + receiverType + "' target='_blank'><span style='font-family:Arial;color:rgb(70,52,255);font-size:12px'><b><u>ACCEPT</u></b></a> to connect with your colleague.</span></span><br />";
            strMailBody = strMailBody + @"<span style=""font-family:Arial;color:rgb(70,52,255);font-size:12px""><ul><li>Doc-Friend is restricted to Doctors and Dentists only. The 'Access Denied' warning will appear if you have not logged in.</li>";
            // strMailBody = strMailBody + @". To retrieve the message, log in to your Personal </span><a href =""http://www.findadoc.com/Community/community.aspx"" target=""_blank""><span style=""font-family:Arial;color:rgb(70,52,255);font-size:22px""><b><u>Doctor Face Page</u></b></a></span></span><br />";
            strMailBody = strMailBody + @"<li>Use your e-mail address as your ID. A temporary password, " + "<i>temp1234,</i>" + " can be substituted if needed. You can register later.</li></ul></span><br />";
            strMailBody = strMailBody + @"<span style=""font-family:Arial;color:rgb(70,52,255);font-size:12px"">The message from " + Session["LoginName"].ToString() + " will appear on your Personal </span>";
            strMailBody = strMailBody + @"<a href =""http://www.findadoc.com/Community/community.aspx"" target=""_blank""><span style=""font-family:Arial;color:rgb(70,52,255);font-size:12px""><b><u>Doctor Face Page</u></b></a></span><br />";
            strMailBody = strMailBody + @"<span><img height=""50"" width=""100"" src=""http://www.findadoc.com/images/logo.jpg""/><span style=""FONT-FAMILY:Arial;COLOR:rgb(0,0,0);FONT-SIZE:12px"">";
            strMailBody = strMailBody + @"<span style=""WHITE-SPACE:pre-wrap""></span></span>&nbsp; &nbsp; <span style=""COLOR:rgb(0,0,0);FONT-SIZE:12px"">&quot;Connect the Docs&quot; on Findadoc</span></span>";
            strSubject = @"Message from " + Session["LoginName"].ToString() + " via Doc Friend @ Findadoc";
            string strMessageStatus = SendEmailToDoctorDentist(strMailBody, strEmailTo, Session["LoginName"].ToString(), strSubject, sUserEmail);
            if (strMessageStatus == "Send Successfully")
            {
                //Response.Write("Message Sent Successfully");
                ClientScript.RegisterStartupScript(typeof(Page), "MessagePopUp", "alert('Message Sent Successfully');", true);
            }
            else
            {
                // Response.Write(strMessageStatus);
                ClientScript.RegisterStartupScript(typeof(Page), "MessagePopUp", "alert('" + strMessageStatus + "');", true);
            }
        }
    }
    private void NewMail(int Id, int recieverId, string drImage, string type)
    {
        string DoctorOrDentist = Session["isToDoctorOrDentist"].ToString();
        if (DoctorOrDentist == "Doctor")
        {
            receiverType = "doctor";
            strMailBody = @"<div style='float:left;margin-right:15px;margin-bottom:5px'><span>" + drImage + "</span></div><br />";
            strMailBody = strMailBody + @"<span style=""font-size:12px""><span style='font-family:Arial;color:rgb(70,52,255);font-size:12px'>" + Session["LoginName"].ToString() + " has sent a new message for you <br />";
            strMailBody = strMailBody + @"Click on <a href='http://www.findadoc.com/doctor/doctorLogin.aspx?id=" + Id + "&recieverId=" + recieverId + "&type=" + type + "&receiverType=" + receiverType + "'target='_blank'><span style='font-family:Arial;color:rgb(70,52,255);font-size:12px'><b><u>OPEN</u></b></a> to view message on your Secure FacePage .</span></span><br />";
            strMailBody = strMailBody + @"<span style=""font-family:Arial;color:rgb(70,52,255);font-size:12px"">The message from " + Session["LoginName"].ToString() + " will appear on your Personal </span>";
            strMailBody = strMailBody + @"<a href =""http://www.findadoc.com/Community/community.aspx"" target=""_blank""><span style=""font-family:Arial;color:rgb(70,52,255);font-size:12px""><b><u>Doctor Face Page</u></b></a></span><br />";
            strMailBody = strMailBody + @"<span><img height=""50"" width=""100"" src=""http://www.findadoc.com/images/logo.jpg""/><span style=""FONT-FAMILY:Arial;COLOR:rgb(0,0,0);FONT-SIZE:12px"">";
            strMailBody = strMailBody + @"<span style=""WHITE-SPACE:pre-wrap""></span></span>&nbsp; &nbsp; <span style=""COLOR:rgb(0,0,0);FONT-SIZE:12px"">&quot;Connect the Docs&quot; on Findadoc</span></span>";
            strSubject = @"Message from " + Session["LoginName"].ToString() + " via Doc Friend @ Findadoc";
            string strMessageStatus = SendEmailToDoctorDentist(strMailBody, strEmailTo, Session["LoginName"].ToString(), strSubject, sUserEmail);
            if (strMessageStatus == "Send Successfully")
            {
                ClientScript.RegisterStartupScript(typeof(Page), "MessagePopUp", "alert('Message Sent Successfully');", true);
            }
            else
            {
                ClientScript.RegisterStartupScript(typeof(Page), "MessagePopUp", "alert('" + strMessageStatus + "');", true);
            }
        }
        else if (DoctorOrDentist == "Dentist")
        {
            receiverType = "dentist";
            strMailBody = @"<div style='float:left;margin-right:15px;margin-bottom:5px'><span>" + drImage + "</span></div><br />";

            strMailBody = strMailBody + @"<span style=""font-size:12px""><span style='font-family:Arial;color:rgb(70,52,255);font-size:12px'>" + Session["LoginName"].ToString() + "has sent a new message for you.<br />";
            strMailBody = strMailBody + @"Click on <a href='http://www.findadoc.com/Dentist/DentistLogin.aspx?id=" + Id + "&recieverId=" + recieverId + "&type=" + type + "&receiverType=" + receiverType + "' target='_blank'><span style='font-family:Arial;color:rgb(70,52,255);font-size:12px'><b><u>OPEN</u></b></a> to view the message.</span></span><br />";
            strMailBody = strMailBody + @"<span style=""font-family:Arial;color:rgb(70,52,255);font-size:12px"">The message from " + Session["LoginName"].ToString() + " will appear on your Personal </span>";
            strMailBody = strMailBody + @"<a href =""http://www.findadoc.com/Community/community.aspx"" target=""_blank""><span style=""font-family:Arial;color:rgb(70,52,255);font-size:12px""><b><u>Your Secure Face Page</u></b></a></span><br />";
            strMailBody = strMailBody + @"<span><img height=""50"" width=""100"" src=""http://www.findadoc.com/images/logo.jpg""/><span style=""FONT-FAMILY:Arial;COLOR:rgb(0,0,0);FONT-SIZE:12px"">";
            strMailBody = strMailBody + @"<span style=""WHITE-SPACE:pre-wrap""></span></span>&nbsp; &nbsp; <span style=""COLOR:rgb(0,0,0);FONT-SIZE:12px"">&quot;Connect the Docs&quot; on Findadoc</span></span>";
            strSubject = @"Message from " + Session["LoginName"].ToString() + " via Doc Friend @ Findadoc";
            string strMessageStatus = SendEmailToDoctorDentist(strMailBody, strEmailTo, Session["LoginName"].ToString(), strSubject, sUserEmail);
            if (strMessageStatus == "Send Successfully")
            {
                //Response.Write("Message Sent Successfully");
                ClientScript.RegisterStartupScript(typeof(Page), "MessagePopUp", "alert('Message Sent Successfully');", true);
            }
            else
            {
                // Response.Write(strMessageStatus);
                ClientScript.RegisterStartupScript(typeof(Page), "MessagePopUp", "alert('" + strMessageStatus + "');", true);
            }
        }
    }

    private void AcceptFriendshipMail(int Id, int recieverId, string drImage, string type)
    {
        string DoctorOrDentist = Session["isToDoctorOrDentist"].ToString();
        if (DoctorOrDentist == "Doctor")
        {
            receiverType = "doctor";
            strMailBody = @"<div style='float:left;margin-right:15px;margin-bottom:5px'><span>" + drImage + "</span></div><br />";
            strMailBody = strMailBody + @"<span style=""font-size:12px""><span style='font-family:Arial;color:rgb(70,52,255);font-size:12px'>" + Session["LoginName"].ToString() + " has accepted your FRIEND REQUEST <br />";
            strMailBody = strMailBody + @"Click on <a href='http://www.findadoc.com/doctor/doctorLogin.aspx?id=" + Id + "&recieverId=" + recieverId + "&type=" + type + "&receiverType=" + receiverType + "'target='_blank'><span style='font-family:Arial;color:rgb(70,52,255);font-size:12px'><b><u>ACCEPT</u></b></a> to connect with your colleague.</span></span><br />";
            strMailBody = strMailBody + @"<span style=""font-family:Arial;color:rgb(70,52,255);font-size:12px""><ul><li>Doc-Friend is restricted to Doctors and Dentists only. The 'Access Denied' warning will appear if you have not logged in.</li>";
            strMailBody = strMailBody + @"<li>Use your e-mail address as your ID. A temporary password, " + "<i>temp1234,</i>" + " can be substituted if needed. You can register later.</li></ul></span><br />";
            strMailBody = strMailBody + @"<span style=""font-family:Arial;color:rgb(70,52,255);font-size:12px"">The message from " + Session["LoginName"].ToString() + " will appear on your Personal </span>";
            strMailBody = strMailBody + @"<a href =""http://www.findadoc.com/Community/community.aspx"" target=""_blank""><span style=""font-family:Arial;color:rgb(70,52,255);font-size:12px""><b><u>Doctor Face Page</u></b></a></span><br />";
            strMailBody = strMailBody + @"<span><img height=""50"" width=""100"" src=""http://www.findadoc.com/images/logo.jpg""/><span style=""FONT-FAMILY:Arial;COLOR:rgb(0,0,0);FONT-SIZE:12px"">";
            strMailBody = strMailBody + @"<span style=""WHITE-SPACE:pre-wrap""></span></span>&nbsp; &nbsp; <span style=""COLOR:rgb(0,0,0);FONT-SIZE:12px"">&quot;Connect the Docs&quot; on Findadoc</span></span>";
            strSubject = @"Message from " + Session["LoginName"].ToString() + " via Doc Friend @ Findadoc";
            string strMessageStatus = SendEmailToDoctorDentist(strMailBody, strEmailTo, Session["LoginName"].ToString(), strSubject, sUserEmail);
            if (strMessageStatus == "Send Successfully")
            {
                ClientScript.RegisterStartupScript(typeof(Page), "MessagePopUp", "alert('Message Sent Successfully');", true);
            }
            else
            {
                ClientScript.RegisterStartupScript(typeof(Page), "MessagePopUp", "alert('" + strMessageStatus + "');", true);
            }
        }
        else if (DoctorOrDentist == "Dentist")
        {
            receiverType = "dentist";
            strMailBody = @"<div style='float:left;margin-right:15px;margin-bottom:5px'><span>" + drImage + "</span></div><br />";

            strMailBody = strMailBody + @"<span style=""font-size:12px""><span style='font-family:Arial;color:rgb(70,52,255);font-size:12px'>" + Session["LoginName"].ToString() + " has accepted your friend request.<br />";
            strMailBody = strMailBody + @"Click on <a href='http://www.findadoc.com/Dentist/DentistLogin.aspx?id=" + Id + "&recieverId=" + recieverId + "&type=" + type + "&receiverType=" + receiverType + "' target='_blank'><span style='font-family:Arial;color:rgb(70,52,255);font-size:12px'><b><u>OPEN</u></b></a> to read the message.</span></span><br />";
           
            strMailBody = strMailBody + @"<span style=""font-family:Arial;color:rgb(70,52,255);font-size:12px"">The message from " + Session["LoginName"].ToString() + " will appear on your Personal </span>";
            strMailBody = strMailBody + @"<a href =""http://www.findadoc.com/Community/community.aspx"" target=""_blank""><span style=""font-family:Arial;color:rgb(70,52,255);font-size:12px""><b><u>Doctor Face Page</u></b></a></span><br />";
            strMailBody = strMailBody + @"<span><img height=""50"" width=""100"" src=""http://www.findadoc.com/images/logo.jpg""/><span style=""FONT-FAMILY:Arial;COLOR:rgb(0,0,0);FONT-SIZE:12px"">";
            strMailBody = strMailBody + @"<span style=""WHITE-SPACE:pre-wrap""></span></span>&nbsp; &nbsp; <span style=""COLOR:rgb(0,0,0);FONT-SIZE:12px"">&quot;Connect the Docs&quot; on Findadoc</span></span>";
            strSubject = @"Message from " + Session["LoginName"].ToString() + " via Doc Friend @ Findadoc";
            string strMessageStatus = SendEmailToDoctorDentist(strMailBody, strEmailTo, Session["LoginName"].ToString(), strSubject, sUserEmail);
            if (strMessageStatus == "Send Successfully")
            {
                //Response.Write("Message Sent Successfully");
                ClientScript.RegisterStartupScript(typeof(Page), "MessagePopUp", "alert('Message Sent Successfully');", true);
            }
            else
            {
                // Response.Write(strMessageStatus);
                ClientScript.RegisterStartupScript(typeof(Page), "MessagePopUp", "alert('" + strMessageStatus + "');", true);
            }
        }
    }
    private void ReplyMail(int Id, int recieverId,string type)
    {
        string DoctorOrDentist = Session["isToDoctorOrDentist"].ToString();
        if (DoctorOrDentist == "Doctor")
        {
            receiverType = "doctor";
            strMailBody = @"<span style=""font-size:12px""><span style='font-family:Arial;color:rgb(70,52,255);font-size:12px'>" + Session["LoginName"].ToString() + " has sent a new message for you <br />";
            strMailBody = strMailBody + @"Click on <a href='http://www.findadoc.com/doctor/doctorLogin.aspx?id=" + Id + "&recieverId=" + recieverId + "&type=" + type + "&receiverType=" + receiverType + "'target='_blank'><span style='font-family:Arial;color:rgb(70,52,255);font-size:12px'><b><u>OPEN</u></b></a> to read the message .</span></span><br />";
            strMailBody = strMailBody + @"<span><img height=""50"" width=""100"" src=""http://www.findadoc.com/images/logo.jpg""/><span style=""FONT-FAMILY:Arial;COLOR:rgb(0,0,0);FONT-SIZE:12px"">";
            strMailBody = strMailBody + @"<span style=""WHITE-SPACE:pre-wrap""></span></span>&nbsp; &nbsp; <span style=""COLOR:rgb(0,0,0);FONT-SIZE:12px"">&quot;Connect the Docs&quot; on Findadoc</span></span>";
            strSubject = @"Message from " + Session["LoginName"].ToString() + " via Doc Friend @ Findadoc";
            string strMessageStatus = SendEmailToDoctorDentist(strMailBody, strEmailTo, Session["LoginName"].ToString(), strSubject, sUserEmail);
            if (strMessageStatus == "Send Successfully")
            {
                ClientScript.RegisterStartupScript(typeof(Page), "MessagePopUp", "alert('Message Sent Successfully');", true);
            }
            else
            {
                ClientScript.RegisterStartupScript(typeof(Page), "MessagePopUp", "alert('" + strMessageStatus + "');", true);
            }
        }
        else if (DoctorOrDentist == "Dentist")
        {
            receiverType = "dentist";
            strMailBody =  @"<span style=""font-size:12px""><span style='font-family:Arial;color:rgb(70,52,255);font-size:12px'>" + Session["LoginName"].ToString() + " has replied to your message.<br />";
            strMailBody = strMailBody + @"Click on <a href='http://www.findadoc.com/Dentist/DentistLogin.aspx?id=" + Id + "&recieverId=" + recieverId + "&type=" + type + "&receiverType=" + receiverType + "' target='_blank'><span style='font-family:Arial;color:rgb(70,52,255);font-size:12px'><b><u>OPEN</u></b></a> to View on your Secure Face Page.</span></span><br />";
            strMailBody = strMailBody + @"<span><img height=""50"" width=""100"" src=""http://www.findadoc.com/images/logo.jpg""/><span style=""FONT-FAMILY:Arial;COLOR:rgb(0,0,0);FONT-SIZE:12px"">";
            strMailBody = strMailBody + @"<span style=""WHITE-SPACE:pre-wrap""></span></span>&nbsp; &nbsp; <span style=""COLOR:rgb(0,0,0);FONT-SIZE:12px"">&quot;Connect the Docs&quot; on Findadoc</span></span>";
            strSubject = @"Message from " + Session["LoginName"].ToString() + " via Doc Friend @ Findadoc";
            string strMessageStatus = SendEmailToDoctorDentist(strMailBody, strEmailTo, Session["LoginName"].ToString(), strSubject, sUserEmail);
            if (strMessageStatus == "Send Successfully")
            {
                //Response.Write("Message Sent Successfully");
                ClientScript.RegisterStartupScript(typeof(Page), "MessagePopUp", "alert('Message Sent Successfully');", true);
            }
            else
            {
                // Response.Write(strMessageStatus);
                ClientScript.RegisterStartupScript(typeof(Page), "MessagePopUp", "alert('" + strMessageStatus + "');", true);
            }
        }
    }

    protected void grdMessages_PageIndexChanging(object sender, GridViewPageEventArgs e)
    {
        grdMessages.PageIndex = e.NewPageIndex;
        BindGrid(Convert.ToInt32(Session["userID"]));
    }


    // delete confirmation
    protected void grdMessages_RowDataBound(object sender, GridViewRowEventArgs e)
    {
        try
        {
            if (e.Row.RowType == DataControlRowType.DataRow)
            {
                string id = grdMessages.DataKeys[e.Row.RowIndex].Value.ToString();
                LinkButton btnOpen = (LinkButton)e.Row.Cells[2].FindControl("btnHaveRead");
                LinkButton btnread = (LinkButton)e.Row.Cells[2].FindControl("lnkRead");
                FacePage fp = CustomRepository.GetFaceGageMessage(Convert.ToInt32(id));
                if (fp.IsRead == true)
                {
                    btnOpen.Visible = true;
                    btnread.Visible = false;
                    
                }
               
                
            }





            if (e.Row.RowType == DataControlRowType.DataRow)
            {
                LinkButton lnk = (LinkButton)e.Row.FindControl("lnkDelete");

                try
                {
                    string id = grdMessages.DataKeys[e.Row.RowIndex].Value.ToString();
                    lnk.Attributes.Add("onclick", "return confirm('Are you sure to delete this Face Page?')");
                }
                catch (Exception es)
                {
                    Response.Write(es.ToString());
                }
            }
        }
        catch (Exception ex)
        {
            Response.Write(ex.ToString());
        }
    }
    protected void grdMessages_RowDeleting(object sender, GridViewDeleteEventArgs e)
    {
        try
        {
            string id = grdMessages.DataKeys[e.RowIndex].Value.ToString();
            string delSql;
            if (Session["DentistDoctorID"] == null)
            {
                delSql = "delete from FacePage where ReceiverID=" + Convert.ToInt32(Session["userID"]) + " and id=" + id + "";
                mgr.ExecuteQuery(delSql);
                BindGrid(Convert.ToInt32(Session["userID"]));
                btnSubmitt.Text = "Post";
                clear_blockEditor();
            }
            //else
            {
                //    Response.Write(@"<script language='javascript'>alert('You are not allowed to delete any other Doctor FacePage.')</script>");
            }
            // delSql = "delete from FacePage where doctorID=" + Convert.ToInt32(Session["DentistDoctorID"]) + " and UserID=" + Convert.ToInt32(Session["userID"]) + " and id=" + id + ""; Commented By Wahaj Khan
        }
        catch (Exception ex)
        {
            Response.Write(ex.ToString());
        }
    }
    protected void grdMessages_RowCommand(object sender, GridViewCommandEventArgs e)
    {
        
        if (e.CommandName.ToString().ToUpper().Trim() == "Read".ToUpper().Trim())
        {
            string id = e.CommandArgument.ToString();
            FacePage fp = CustomRepository.GetFaceGageMessage(Convert.ToInt32(id));
            txtFacePageTitle.Text = fp.FacePageTitle;
            txtDescription.Text = fp.FacePageMessage;
            bool isRead = true;
            CustomRepository.UpdateFacepage(Convert.ToInt32(id),isRead);
            btnSubmitt.Visible = false;
            ckEditBlock.Visible = true;
            Control ctrl = e.CommandSource as Control;
            if (ctrl != null)
            {
                GridViewRow row = ctrl.Parent.NamingContainer as GridViewRow;
                //LinkButton fullname = (LinkButton)row.FindControl("lbName");
                LinkButton lnkBread = (LinkButton)row.FindControl("lnkRead");
                lnkBread.Visible = false;
                LinkButton lnkBhaveRead = (LinkButton)row.FindControl("btnHaveRead");
                lnkBhaveRead.Visible = true;
            }
            
          
                if (fp.SenderType == 2)
                {
                    tbl_Doctor doc = CustomRepository.GetReceiverDoctor(Convert.ToInt32(fp.SenderID));
                    string fullName = doc.FName + " " + doc.MName + " " + doc.LName;
                    lblPostTitle.Text = "Message From:" + "" + fullName;
                  
                }
                else
                {
                    tbl_Dentist doc = CustomRepository.GetReceiverDentists(Convert.ToInt32(fp.SenderID));
                    string fullName = doc.FName + " " + doc.MName + " " + doc.LName;
                    lblPostTitle.Text = "Message From:" + "" + fullName;
                    
                }
           



        }

        else if (e.CommandName.ToString().ToUpper().Trim() == "Reply".ToUpper().Trim())
        {

            string id = e.CommandArgument.ToString();
            FacePage fp = CustomRepository.GetFaceGageMessage(Convert.ToInt32(id));
            ViewState["Id"] = id;
            Session["isReply"] = "true";
            Session["AcceptRequest"] = "Reply";
            txtFacePageTitle.Text = "Re-" + fp.FacePageTitle;
            if (fp.ReceiverType == 2)
            {
                if (fp.SenderType == 2)
                {
                    tbl_Doctor doc = CustomRepository.GetReceiverDoctor(Convert.ToInt32(fp.SenderID));
                    string fullName = doc.FName + " " + doc.MName + " " + doc.LName;
                    lblPostTitle.Text = "Reply to:" + "" + fullName;
                    ckEditBlock.Visible = true;
                    txtDescription.Text = "";
                    btnSubmitt.Visible = true;
                    Session["isToDoctorOrDentist"] = "Doctor";
                }
                else
                {
                    tbl_Dentist doc = CustomRepository.GetReceiverDentists(Convert.ToInt32(fp.SenderID));
                    string fullName = doc.FName + " " + doc.MName + " " + doc.LName;
                    lblPostTitle.Text = "Reply to:" + "" + fullName;
                    ckEditBlock.Visible = true;
                    txtDescription.Text = "";
                    btnSubmitt.Visible = true;
                    Session["isToDoctorOrDentist"] = "Dentist";
                }
            }
            else
            {
                if (fp.SenderType == 2)
                {
                    tbl_Doctor doc = CustomRepository.GetReceiverDoctor(Convert.ToInt32(fp.SenderID));
                    string fullName = doc.FName + " " + doc.MName + " " + doc.LName;
                    lblPostTitle.Text = "Reply to:" + "" + fullName;
                    ckEditBlock.Visible = true;
                    txtDescription.Text = "";
                    btnSubmitt.Visible = true;
                    Session["isToDoctorOrDentist"] = "Doctor";
                }
                else
                {
                    tbl_Dentist doc = CustomRepository.GetReceiverDentists(Convert.ToInt32(fp.SenderID));
                    string fullName = doc.FName + " " + doc.MName + " " + doc.LName;
                    lblPostTitle.Text = "Reply to:" + "" + fullName;
                    ckEditBlock.Visible = true;
                    txtDescription.Text = "";
                    btnSubmitt.Visible = true;
                    Session["isToDoctorOrDentist"] = "Dentists";
                }
            }

        }

      
    }
    private void Reply()
    {
        try
        {
            int id = Convert.ToInt32(ViewState["Id"]);
            FacePage fpS = CustomRepository.GetFaceGageMessage(id);
            FacePage fp = new FacePage();
            fp.FacePageMessage = txtDescription.Text.Trim();
            fp.FacePagePostedDate = System.DateTime.Now;
            fp.FacePageReplyMessage = "";
            fp.FacePageTitle = txtFacePageTitle.Text.ToString().Trim();


            fp.ReceiverID = fpS.SenderID;
            fp.ReceiverType = fpS.SenderType;
            fp.SenderID = fpS.ReceiverID;
            fp.SenderType = Convert.ToByte(fpS.ReceiverType);
            fp.IsRead = false;
            CustomRepository.AddReplyMessage(fp);
            int receverID =Convert.ToInt32(fp.ReceiverID);
            int senderId = Convert.ToInt32(fp.SenderID);
            strEmailTo = GetUserEmailAddress(receverID,Convert.ToInt32(fp.ReceiverType));
            sUserEmail = GetSenderEmailAddress(senderId, Convert.ToInt32(fp.SenderType));
            string type = "";
            if (fp.ReceiverType ==2)
            {
                type = "Doctor";
            }
            else
            {
                type = "Dentist";
            }
            if (Session["UserEmail"] != null && Session["UserEmail"].ToString().Trim() != "")
            {
                sUserEmail = Session["UserEmail"].ToString(); //This is Email From Address 
            }
            ReplyMail(senderId, receverID,type);
            
            lblMessage.Visible = true;
            lblMessage.Text = "Message has been Inserted successfully.";
            lblMessage.Font.Bold = true;
            clear_blockEditor();
            ckEditBlock.Visible = false;
        }
        catch
        {
            lblMessage.Visible = true;
            lblMessage.Text = "Message can not be Inserted.";
            lblMessage.Font.Bold = true;
            clear_blockEditor();
        }

      
    }
    protected void clear_blockEditor()
    {
        txtDescription.Text = "";
        txtFacePageTitle.Text = "";
        txtPostReply.Text = "";
        txtPostReply.Visible = false;
    }

    protected void lnkNewEntry_Click(object sender, EventArgs e)
    {
        btnSubmitt.Text = "Post";
        clear_blockEditor();
    }
    protected string SendEmailToDoctorDentist(string strBody, string strTo, string fromName, string strSubject, string strFrom)
    {
        SmtpClient smtpClient = new SmtpClient();
        MailMessage message = new MailMessage();
        try
        {
            message.From = new MailAddress(strFrom);
            message.Subject = strSubject;
            message.Body = strBody;
            message.IsBodyHtml = true;
            smtpClient.Host = "smtp.1and1.com"; //Or Your SMTP Server Address
            smtpClient.Credentials = new System.Net.NetworkCredential("docfriend@findadoc.com", "rateddoc56832013");
            message.To.Add(strTo);
            smtpClient.EnableSsl = true;
            smtpClient.Send(message);
            message = null;
            smtpClient = null;
            return "Send Successfully";
           
        }
        catch (Exception ex)
        {
            return ex.Message;
        }
    }
    protected string GetUserEmailAddress(int id,int Type)
    {
        string strEmailTo = "";
        try
        {
           if(Type==2)
            {
                SqlParameter[] sqlParam = new SqlParameter[1];
                sqlParam[0] = new SqlParameter("@dr_id", SqlDbType.Int);
                sqlParam[0].Value = id;
                DataSet ds_drdet = mgr.ExecuteQuery("get_doctordetails", sqlParam, "tbl_a");
                if (ds_drdet.Tables[0].Rows.Count > 0)
                    strEmailTo = ds_drdet.Tables[0].Rows[0]["email"].ToString();
                else
                    strEmailTo = "";
            }
            else if(Type==4)
            {
                SqlParameter[] sqlParam = new SqlParameter[1];
                sqlParam[0] = new SqlParameter("@dnt_id", SqlDbType.Int);
                sqlParam[0].Value = id;
                DataSet ds_drdet = mgr.ExecuteQuery("get_dentistdetails", sqlParam, "tbl_a");
                if (ds_drdet.Tables[0].Rows.Count > 0)
                    strEmailTo = ds_drdet.Tables[0].Rows[0]["email"].ToString();
                else
                    strEmailTo = "";
            }
            else
            {
                strEmailTo = "docfriend@findadoc.com";
            }
            return strEmailTo;
        }
        catch (Exception ex)
        {
            return ex.Message;
        }
    }
    protected string GetSenderEmailAddress(int id, int Type)
    {
        string strEmailTo = "";
        try
        {
            if (Type == 2)
            {
                SqlParameter[] sqlParam = new SqlParameter[1];
                sqlParam[0] = new SqlParameter("@dr_id", SqlDbType.Int);
                sqlParam[0].Value = id;
                DataSet ds_drdet = mgr.ExecuteQuery("get_doctordetails", sqlParam, "tbl_a");
                if (ds_drdet.Tables[0].Rows.Count > 0)
                    strEmailTo = ds_drdet.Tables[0].Rows[0]["email"].ToString();
                else
                    strEmailTo = "";
            }
            else if (Type == 4)
            {
                SqlParameter[] sqlParam = new SqlParameter[1];
                sqlParam[0] = new SqlParameter("@dnt_id", SqlDbType.Int);
                sqlParam[0].Value = id;
                DataSet ds_drdet = mgr.ExecuteQuery("get_dentistdetails", sqlParam, "tbl_a");
                if (ds_drdet.Tables[0].Rows.Count > 0)
                    strEmailTo = ds_drdet.Tables[0].Rows[0]["email"].ToString();
                else
                    strEmailTo = "";
            }
            else
            {
                strEmailTo = "docfriend@findadoc.com";
            }
            return strEmailTo;
        }
        catch (Exception ex)
        {
            return ex.Message;
        }
    }

    protected string GetUserName(int id,int Type)
    {
        string strName = "";
        try
        {
            //Fill Doctor Name and his/her speciality in your account box 
            //if (Session["DoctorType"].ToString().ToUpper() == "Doctor".ToUpper())
            if (Type == 2)
            {
                SqlParameter[] sqlParam = new SqlParameter[1];
                sqlParam[0] = new SqlParameter("@dr_id", SqlDbType.Int);
                sqlParam[0].Value = id;
                DataSet ds_drdet = mgr.ExecuteQuery("get_doctordetails", sqlParam, "tbl_a");
                if (ds_drdet.Tables[0].Rows.Count > 0)
                    strName = ds_drdet.Tables[0].Rows[0]["Name"].ToString();
                else
                    strName = "";
            }
            //else if (Session["DoctorType"].ToString().ToUpper() == "Dentist".ToUpper())
            else if (Type == 4)
            {
                SqlParameter[] sqlParam = new SqlParameter[1];
                sqlParam[0] = new SqlParameter("@dnt_id", SqlDbType.Int);
                sqlParam[0].Value = id;
                DataSet ds_drdet = mgr.ExecuteQuery("get_dentistdetails", sqlParam, "tbl_a");
                if (ds_drdet.Tables[0].Rows.Count > 0)
                    strName = ds_drdet.Tables[0].Rows[0]["Name"].ToString();
                else
                    strName = "";
            }
            else
            {
                strName = "";
            }
            return strName;
        }
        catch (Exception ex)
        {
            return ex.Message;
        }
    }

    public string getPhoto(object photo, object sex)
    {
        string p = photo.ToString();
        if (p.Length > 0)
        {


            if (File.Exists(Request.PhysicalApplicationPath + "\\images\\Dr_images\\" + photo))
            {
                //string str_path = mgr.getThumbnaleImage(Session["strHttp"].ToString() + "images/Dr_images/" + photo, 80, 100, false, "");
                string DoctorOrDentist = Convert.ToString(Session["isDoctorOrDentist"]);
                if (DoctorOrDentist == "Doctor")
                {
                    string str_path = getThumbnaleImageWithURLFormat(photo.ToString(), 50, 60, false, "", Session["strHTTP"].ToString());
                    return str_path;
                }
                else
                {
                    string str_path = getDentThumbnaleImageWithURLFormat(photo.ToString(), 50, 60, false, "", Session["strHTTP"].ToString());
                    return str_path;
                    
                }
            }
            else
            {
                if (sex.ToString().ToLower() == "m")
                    return "<img height=\"60\" width=\"50\" src='" + Session["strHttp"].ToString() + "images/Dr_images/silhouette-male.gif'>";
                else
                    return "<img height=\"60\" width=\"50\" src='" + Session["strHttp"].ToString() + "images/Dr_images/silhouette--female.gif'>";
            }







        }
        else
        {
            if (sex.ToString().ToLower() == "m")
                return "<img height=\"60\" width=\"50\" src='" + Session["strHttp"].ToString() + "images/Dr_images/silhouette-male.gif'>";
            else
                return "<img height=\"60\" width=\"50\" src='" + Session["strHttp"].ToString() + "images/Dr_images/silhouette--female.gif'>";
        }
    }
    public string getThumbnaleImageWithURLFormat(string imgName, int maxWidth, int maxHeight, bool saveImage, string savePath, string baseURL)
    {
        string s;
        double imgHeight, imgWidth;
        //Response.Write(imgName) ;
        s = Server.MapPath("~/images/dr_images/"+imgName);
        //Response.Write("</br>"+s);
        System.Drawing.Image currentImage = System.Drawing.Image.FromFile(s);
        imgHeight = currentImage.Height;
        imgWidth = currentImage.Width;
        if (imgWidth > maxWidth | imgHeight > maxHeight)
        {
            double deltaWidth = imgWidth - maxWidth;
            double deltaHeight = imgHeight - maxHeight;
            double scaleFactor;
            if (deltaHeight > deltaWidth)
                scaleFactor = maxHeight / imgHeight;
            else
                scaleFactor = maxWidth / imgWidth;
            imgWidth *= scaleFactor;
            imgHeight *= scaleFactor;
        }

        if (saveImage)
        {
            if (savePath == "")
                throw new Exception("must pass a file name");
            currentImage.GetThumbnailImage(Convert.ToInt32(imgWidth), Convert.ToInt32(imgHeight), null, IntPtr.Zero).Save(Server.MapPath(savePath));
            currentImage.Dispose();
        }
        //return currentImage.GetThumbnailImage(Convert.ToInt32(imgWidth), Convert.ToInt32(imgHeight), null, IntPtr.Zero);
        return ("<img height=\"60\" width=\"50\" src='"+Session["strHttp"].ToString()+"images/Dr_images/"+imgName+"'>");
       // return ("<img src=\"" + baseURL + "images/dr_images/" + imgName + "\"" + " height=\"" + imgHeight + "\" width=\"" + imgWidth + "\" border='0' alt=''/>");
    }
    public string getDentThumbnaleImageWithURLFormat(string imgName, int maxWidth, int maxHeight, bool saveImage, string savePath, string baseURL)
    {
        string s;
        double imgHeight, imgWidth;
        //Response.Write(imgName) ;
        s = Server.MapPath("~/images/Dnt_images/" + imgName);
        //Response.Write("</br>"+s);
        System.Drawing.Image currentImage = System.Drawing.Image.FromFile(s);
        imgHeight = currentImage.Height;
        imgWidth = currentImage.Width;
        if (imgWidth > maxWidth | imgHeight > maxHeight)
        {
            double deltaWidth = imgWidth - maxWidth;
            double deltaHeight = imgHeight - maxHeight;
            double scaleFactor;
            if (deltaHeight > deltaWidth)
                scaleFactor = maxHeight / imgHeight;
            else
                scaleFactor = maxWidth / imgWidth;
            imgWidth *= scaleFactor;
            imgHeight *= scaleFactor;
        }

        if (saveImage)
        {
            if (savePath == "")
                throw new Exception("must pass a file name");
            currentImage.GetThumbnailImage(Convert.ToInt32(imgWidth), Convert.ToInt32(imgHeight), null, IntPtr.Zero).Save(Server.MapPath(savePath));
            currentImage.Dispose();
        }
        //return currentImage.GetThumbnailImage(Convert.ToInt32(imgWidth), Convert.ToInt32(imgHeight), null, IntPtr.Zero);
        return ("<img height=\"60\" width=\"50\" src='"+Session["strHttp"].ToString()+"images/Dnt_images/"+imgName+"'>");
        // return ("<img src=\"" + baseURL + "images/dr_images/" + imgName + "\"" + " height=\"" + imgHeight + "\" width=\"" + imgWidth + "\" border='0' alt=''/>");
    }
    private DataSet GetDoctorPhoto()
    {
        string type = "";
        string DoctorOrDentist = Convert.ToString(Session["isDoctorOrDentist"]);
        string doctorID = Session["userID"].ToString();
        DataSet ds;
        if (!string.IsNullOrEmpty(Convert.ToString(Session["FeatureType"])))
        {
             type = Convert.ToString(Session["FeatureType"]);
        }
        if (DoctorOrDentist == "Doctor")
        {
            tbl_Doctor doc = CustomRepository.GetReceiverDoctor(Convert.ToInt32(Session["userID"]));
            if(doc.FeatureDocTypeId==0)
            {
            //if (Convert.ToString(Session["FeatureType"]) == "nonFeatured")
            //{
                
                ds = mgr.ExecuteQuery(returnSqlNonFeatured(doctorID), "tbl_drdet");
            }
            else
            {
                ds = mgr.ExecuteQuery(returnSql(doctorID), "tbl_drdet");
            }
        }
        else
        {
            tbl_Dentist doc = CustomRepository.GetReceiverDentists(Convert.ToInt32(Session["userID"]));
          //  if (Convert.ToString(Session["FeatureType"]) == "nonFeatured")
            if (doc.FeatureDocTypeId == 0)
            {
                ds = mgr.ExecuteQuery(returnSqNonlFeaturedDen(doctorID), "tbl_drdet");
            }
            else
            {
                ds = mgr.ExecuteQuery(returnSqlDen(doctorID), "tbl_drdet");
            }
        }
     
      return ds;
        
    }
    string returnSql(string ids)
    {
        //        //Response.Write(ids); 
        //        Manager mgr = new Manager(true,"ConnectionString");
        string strSql = @"select qu from func_rating()";
        SqlDataReader dr = mgr.ExecuteQuery(strSql);
        System.String orderClause = "";
        System.String AttachMiles = "";
        //        System.String OrderBy = "id";

        if (Session["Travel_Dis"].ToString() != "" && Session["Travel_Dis"] != null) //  to order the result first by Distance and then by rating Desc / to Calculate Miles
        {
            orderClause = "order by Distance ASC, Rating Desc";
            AttachMiles = " , (dbo.GetDistanceInMiles('" + Session["ZipCode"].ToString() + "','" + Session["City"].ToString() + "','" + Session["State"].ToString() + "',zipcodeforsearch)) as Distance";
        }
        else
        {
            orderClause = "order by Rating Desc";
            AttachMiles = ",'' as distance";
        }
        if (dr.Read())
        {
            strSql = @"select d.city, d.zipcode,  
                        case when (select tbl_primaryspeciality.name from tbl_primaryspeciality where 
    						tbl_primaryspeciality.name not in(Sp.name) and tbl_primaryspeciality.id=d.primaryspecialityid) is null
	                    then 
		                    (select tbl_secondaryspeciality.name from tbl_secondaryspeciality where
						    tbl_secondaryspeciality.id=d.secondaryspecialityid)
	                    else
		                    (select tbl_primaryspeciality.name from tbl_primaryspeciality where 
						    tbl_primaryspeciality.name not in(Sp.name) and tbl_primaryspeciality.id=d.primaryspecialityid)
	                    end 
                        as SubSpec,
                        rtrim((select name from tbl_states where stateId = d.state)) as state,
                        Sp.name as specialityName,
                        CAST((" + dr[0].ToString() + @") as numeric(8,2)) as Rating,d.id as id,fname+' '+isnull(mname,'')+' '+lname as docname,address1+'<br>'+city+', '+state as address,
                         Sp.name+isnull(', '+(select tbl_primaryspeciality.name from tbl_primaryspeciality where 
						tbl_primaryspeciality.name not in(Sp.name) and tbl_primaryspeciality.id=d.primaryspecialityid)
						 ,'')+
						isnull(', ' + (select tbl_secondaryspeciality.name from tbl_secondaryspeciality where
						tbl_secondaryspeciality.name not in(Sp.name,p.name) and
						 tbl_secondaryspeciality.id=d.secondaryspecialityid )
                        ,'')
                        as speciality,
                        isnull(dp.website,'')as website,isnull(dp.photo,'') as photo,d.gender " + AttachMiles + @" 
                        from tbl_doctors d
                        left outer join tbl_primaryspeciality p on p.id=d.primaryspecialityid 
                        left outer join tbl_secondaryspeciality s on s.id=d.secondaryspecialityid 
                        left outer join tbl_DrPremium dp on dp.dr_id=d.id
                        left outer join tbl_speciality sp on sp.id=D.specialityid                        
                        where  d.isdelete=0 and d.id in (" + ids + ")" + orderClause; //Km/Ad        
        }
        dr.Close();
        return strSql;

    }
    string returnSqlNonFeatured(string ids)
    {
        //        //Response.Write(ids); 
        //        Manager mgr = new Manager(true,"ConnectionString");
        string strSql = @"select qu from func_rating()";
        SqlDataReader dr = mgr.ExecuteQuery(strSql);
        System.String orderClause = "";
        System.String AttachMiles = "";
        //        System.String OrderBy = "id";

        if (Session["Travel_Dis"].ToString() != "" && Session["Travel_Dis"] != null) //  to order the result first by Distance and then by rating Desc / to Calculate Miles
        {
            orderClause = "order by Distance ASC, Rating Desc";
            AttachMiles = " , (dbo.GetDistanceInMiles('" + Session["ZipCode"].ToString() + "','" + Session["City"].ToString() + "','" + Session["State"].ToString() + "',zipcodeforsearch)) as Distance";
        }
        else
        {
            orderClause = "order by Rating Desc";
            AttachMiles = ",'' as distance";
        }
        if (dr.Read())
        {
            strSql = @"select d.city, d.zipcode,  
                        case when (select tbl_primaryspeciality.name from tbl_primaryspeciality where 
    						tbl_primaryspeciality.name not in(Sp.name) and tbl_primaryspeciality.id=d.primaryspecialityid) is null
	                    then 
		                    (select tbl_secondaryspeciality.name from tbl_secondaryspeciality where
						    tbl_secondaryspeciality.id=d.secondaryspecialityid)
	                    else
		                    (select tbl_primaryspeciality.name from tbl_primaryspeciality where 
						    tbl_primaryspeciality.name not in(Sp.name) and tbl_primaryspeciality.id=d.primaryspecialityid)
	                    end 
                        as SubSpec,
                        rtrim((select name from tbl_states where stateId = d.state)) as state,
                        Sp.name as specialityName,
                        CAST((" + dr[0].ToString() + @") as numeric(8,2)) as Rating,d.id as id,fname+' '+isnull(mname,'')+' '+lname as docname,address1+'<br>'+city+', '+state as address,
                         Sp.name+isnull(', '+(select tbl_primaryspeciality.name from tbl_primaryspeciality where 
						tbl_primaryspeciality.name not in(Sp.name) and tbl_primaryspeciality.id=d.primaryspecialityid)
						 ,'')+
						isnull(', ' + (select tbl_secondaryspeciality.name from tbl_secondaryspeciality where
						tbl_secondaryspeciality.name not in(Sp.name,p.name) and
						 tbl_secondaryspeciality.id=d.secondaryspecialityid )
                        ,'')
                        as speciality,
                        isnull(dp.website,'')as website,isnull(d.photo,'') as photo,d.gender " + AttachMiles + @" 
                        from tbl_doctors d
                        left outer join tbl_primaryspeciality p on p.id=d.primaryspecialityid 
                        left outer join tbl_secondaryspeciality s on s.id=d.secondaryspecialityid 
                        left outer join tbl_DrPremium dp on dp.dr_id=d.id
                        left outer join tbl_speciality sp on sp.id=D.specialityid                        
                        where  d.isdelete=0 and d.id in (" + ids + ")" + orderClause; //Km/Ad        
        }
        dr.Close();
        return strSql;

    }
    string returnSqlDen(string ids)
    {
        //Response.Write(ids);
        Manager mgr = new Manager(true, "ConnectionString");
        string strSql = @"SELECT QU FROM DENTIST_FUNC_RATING()";

        SqlDataReader dr = mgr.ExecuteQuery(strSql);
        System.String orderClause = "";
        System.String AttachMiles = "";
        if (Session["Travel_Dis"].ToString() != "" && Session["Travel_Dis"].ToString() != null) //  to order the result first by Distance and then by rating Desc / to Calculate Miles
        {
            orderClause = "order by Distance ASC, Rating Desc";
            AttachMiles = " , (dbo.GetDistanceInMiles('" + Session["ZipCode"].ToString() + "','" + Session["City"].ToString() + "','" + Session["State"].ToString() + "',zipcodesearch)) as Distance";

        }
        else
        {
            orderClause = "order by Rating Desc";
            AttachMiles = ",'' as distance";
        }

        if (dr.Read())
        {
            strSql = @"select d.city, d.zipcode, sp.specialty as specialityName,
            (select tbl_DentistSubSpecialty.specialty from tbl_DentistSubSpecialty where
			 tbl_DentistSubSpecialty.specialty not in(Sp.specialty) and
			 tbl_DentistSubSpecialty.id=d.secondaryspecialityid)
             as SubSpec,
             rtrim((select name from tbl_states where stateId = d.state)) as state,
            CAST((" + dr[0].ToString() + @") as numeric(8,2)) as rating,d.id as id,fname + ' ' + mname + ' ' + lname as docname, address1 + '<br>' + city + ', ' + state as address,
             Sp.specialty + isnull(', ' + (select tbl_DentistSubSpecialty.specialty from tbl_DentistSubSpecialty where
			tbl_DentistSubSpecialty.specialty not in(Sp.specialty) and
			 tbl_DentistSubSpecialty.id=d.secondaryspecialityid),'') as speciality,
            isnull(dp.website,'')as website,isnull(dp.photo,'') as photo,d.gender" + AttachMiles +
            " from tbl_Dentists d "
                //            + " left outer join tbl_secondaryspeciality s on s.id=d.secondaryspecialityid "
            + " left outer join tbl_DentistSubSpecialty s on s.id=d.secondaryspecialityid "
            + " left outer join tbl_dntpremium dp on dp.dnt_id=d.id "
            + " left outer join tbl_dentistspecialty sp on sp.id=D.specialityid "
             + " where  d.isdelete=0 and d.id in (" + ids + ") " + orderClause;


        }

        return strSql;
    }
    string returnSqNonlFeaturedDen(string ids)
    {
        //Response.Write(ids);
        Manager mgr = new Manager(true, "ConnectionString");
        string strSql = @"SELECT QU FROM DENTIST_FUNC_RATING()";

        SqlDataReader dr = mgr.ExecuteQuery(strSql);
        System.String orderClause = "";
        System.String AttachMiles = "";
        if (Session["Travel_Dis"].ToString() != "" && Session["Travel_Dis"].ToString() != null) //  to order the result first by Distance and then by rating Desc / to Calculate Miles
        {
            orderClause = "order by Distance ASC, Rating Desc";
            AttachMiles = " , (dbo.GetDistanceInMiles('" + Session["ZipCode"].ToString() + "','" + Session["City"].ToString() + "','" + Session["State"].ToString() + "',zipcodesearch)) as Distance";

        }
        else
        {
            orderClause = "order by Rating Desc";
            AttachMiles = ",'' as distance";
        }

        if (dr.Read())
        {
            strSql = @"select d.city, d.zipcode, sp.specialty as specialityName,
            (select tbl_DentistSubSpecialty.specialty from tbl_DentistSubSpecialty where
			 tbl_DentistSubSpecialty.specialty not in(Sp.specialty) and
			 tbl_DentistSubSpecialty.id=d.secondaryspecialityid)
             as SubSpec,
             rtrim((select name from tbl_states where stateId = d.state)) as state,
            CAST((" + dr[0].ToString() + @") as numeric(8,2)) as rating,d.id as id,fname + ' ' + mname + ' ' + lname as docname, address1 + '<br>' + city + ', ' + state as address,
             Sp.specialty + isnull(', ' + (select tbl_DentistSubSpecialty.specialty from tbl_DentistSubSpecialty where
			tbl_DentistSubSpecialty.specialty not in(Sp.specialty) and
			 tbl_DentistSubSpecialty.id=d.secondaryspecialityid),'') as speciality,
            isnull(dp.website,'')as website,isnull(d.photo,'') as photo,d.gender" + AttachMiles +
            " from tbl_Dentists d "
                //            + " left outer join tbl_secondaryspeciality s on s.id=d.secondaryspecialityid "
            + " left outer join tbl_DentistSubSpecialty s on s.id=d.secondaryspecialityid "
            + " left outer join tbl_dntpremium dp on dp.dnt_id=d.id "
            + " left outer join tbl_dentistspecialty sp on sp.id=D.specialityid "
             + " where  d.isdelete=0 and d.id in (" + ids + ") " + orderClause;


        }

        return strSql;
    }
    protected void grgInvitationMsg_PageIndexChanging(object sender, GridViewPageEventArgs e)
    {

    }
    protected void grgInvitationMsg_RowCommand(object sender, GridViewCommandEventArgs e)
    {

    }
    protected void grgInvitationMsg_RowDataBound(object sender, GridViewRowEventArgs e)
    {

    }
    protected void grgInvitationMsg_RowDeleting(object sender, GridViewDeleteEventArgs e)
    {

    }


    protected void btnBackToSearch_Click(object sender, EventArgs e)
    {
        if (Session["DoctorType"].ToString() == "Doctor")
        {
            Response.Redirect(Convert.ToString(Session["strHttps"]) + "Doctor/doctorContent.aspx");
        }
        else
        {
            Response.Redirect(Convert.ToString(Session["strHttps"]) + "Dentist/DentistContent.aspx");
        }
    }
}